package gui;

//Import packages
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

import comparators.AppointmentComparatorBegin;
import comparators.AppointmentComperatorTime;

import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;

import entities.Appointment;
import entities.Calendar;
import fachlogik.Administration;
import fachlogik.CalendarCellRenderer;
import fachlogik.TermineCellRenderer;

import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class CalendarWindow {
	static JFrame frmMain;
	static Container pane;
	static DefaultTableModel mtblCalendar; // Table model
	static JDatePanelImpl pnlMonth;
	static int realYear, realMonth, realDay, currentYear, currentMonth;
	private Appointment selectedAppointment;
	private static DefaultListModel appointmentModel;
	private JButton btn_categories;
	private final JList l_appointments;

	private MainWindow mw;
	private CalendarWindow cw;
	private UserWindow uw;
	private Administration instance;
	private Calendar selectedCalendar;
	private Date selectedDate;
	private DefaultComboBoxModel calendarModel;
	private JPasswordField tf_newPwd;
	private JPasswordField tf_newPwdConfirm;
	private AppointmentDialog ad;
	private CategoryWindow catWindow;
	private EditCalendarWindow eCW;

	public static void main(String[] args) {
		MainWindow mw = new MainWindow();
		JPasswordField jpf = new JPasswordField();
		CalendarWindow cw = new CalendarWindow(mw);
	}

	public CalendarWindow(final MainWindow mw) {
		mw.getTf_password().setText("");
		this.mw = mw;
		this.cw = this;
		this.instance = Administration.getInstance();
		selectedDate = new Date();

		// Look and feel
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
		} catch (InstantiationException e) {
		} catch (IllegalAccessException e) {
		} catch (UnsupportedLookAndFeelException e) {
		}
		appointmentModel = new DefaultListModel();
		calendarModel = new DefaultComboBoxModel();

		// Prepare frame
		frmMain = new JFrame("Calendar"); // Create frame
		// frmMain.setDefaultCloseOperation(1);

		frmMain.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				JFrame frame = (JFrame) e.getSource();

				int result = JOptionPane.showConfirmDialog(frame,
						"Are you sure you want to exit the application?",
						"Exit Application", JOptionPane.YES_NO_OPTION);

				if (result == JOptionPane.YES_OPTION) {
					instance.getUser().setLetzteAnmeldung(cw.selectedDate);
					instance.editPerson(instance.getUser());
					// frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					System.exit(0);
				} else if (result == JOptionPane.NO_OPTION) {
					frmMain.setDefaultCloseOperation(frmMain.DO_NOTHING_ON_CLOSE);
				}
			}
		});

		frmMain.setSize(589, 393); // Set size to 400x400 pixels
		frmMain.setLocationRelativeTo(null);
		pane = frmMain.getContentPane(); // Get content pane
		pane.setLayout(null);
		mtblCalendar = new DefaultTableModel() {
			public boolean isCellEditable(int rowIndex, int mColIndex) {
				return false;
			}
		};

		final UtilDateModel dm = new UtilDateModel();
		pnlMonth = new JDatePanelImpl(dm);
		pnlMonth.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				SimpleDateFormat sf = new SimpleDateFormat("dd.MM.yyyy");
				selectedDate = dm.getValue();
				appointmentsAktualisieren();
			}
		});

		// Set border
		pnlMonth.setBorder(BorderFactory.createTitledBorder("Month"));

		// Add controls to pane
		pane.add(pnlMonth);

		// Set bounds
		pnlMonth.setBounds(0, 0, 280, 200);

		// Make frame visible
		frmMain.setResizable(false);
		frmMain.setVisible(true);

		JPanel pnlDay = new JPanel();
		pnlDay.setBounds(290, 0, 277, 260);
		pnlDay.setBorder(BorderFactory.createTitledBorder("Day"));
		pane.add(pnlDay);
		pnlDay.setLayout(null);

		l_appointments = new JList(appointmentModel);
		l_appointments.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent evt) {
				if (evt.getClickCount() == 2) {
					if (ad == null)
						ad = new AppointmentDialog(selectedAppointment, cw);
				}
			}
		});
		l_appointments.setCellRenderer(new TermineCellRenderer());
		l_appointments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		l_appointments.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				selectedAppointment = (Appointment) l_appointments
						.getSelectedValue();
			}
		});
		JScrollPane scrollPane = new JScrollPane(l_appointments);
		scrollPane.setBounds(12, 25, 255, 225);
		pnlDay.add(scrollPane);

		JButton btn_delete = new JButton("delete...");
		btn_delete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (selectedAppointment != null) {
					instance.removeAppointment(selectedAppointment);
					appointmentsAktualisieren();
				} else
					JOptionPane.showMessageDialog(null,
							"Please choose an appointment!");
			}
		});
		btn_delete.setBounds(460, 270, 106, 25);
		frmMain.getContentPane().add(btn_delete);

		btn_categories = new JButton("Categories");
		btn_categories.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (catWindow == null)
					catWindow = new CategoryWindow(selectedCalendar, cw);
			}
		});
		btn_categories.setBounds(150, 270, 130, 25);
		frmMain.getContentPane().add(btn_categories);

		final JComboBox cb_calendar = new JComboBox(calendarModel);
		cb_calendar.setRenderer(new CalendarCellRenderer());
		cb_calendar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				selectedCalendar = (Calendar) cb_calendar.getSelectedItem();
				appointmentsAktualisieren();
			}
		});
		cb_calendar.setBounds(98, 225, 180, 24);
		frmMain.getContentPane().add(cb_calendar);

		JLabel lblCalendar = new JLabel("Calendar:");
		lblCalendar.setBounds(10, 230, 70, 15);
		frmMain.getContentPane().add(lblCalendar);

		JButton btn_calendars = new JButton("Calendars");
		btn_calendars.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (eCW == null)
					eCW = new EditCalendarWindow(selectedCalendar, cw);
			}
		});
		btn_calendars.setBounds(12, 270, 130, 25);
		frmMain.getContentPane().add(btn_calendars);

		JButton btn_addAppointment = new JButton("Add Appointment");
		btn_addAppointment.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Appointment neu = new Appointment();
				if (selectedCalendar != null) {
					if (ad == null)
						ad = new AppointmentDialog(neu, cw);
				} else
					JOptionPane.showMessageDialog(null,
							"Please choose a Calendar!");
			}
		});
		btn_addAppointment.setBounds(293, 270, 160, 25);
		frmMain.getContentPane().add(btn_addAppointment);

		JButton btnNewButton = new JButton("Logout");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mw.getFrmLogin().setVisible(true);
				instance.getUser().setLetzteAnmeldung(new Date());
				frmMain.dispose();
				if (ad != null) {
					if (ad.isVisible())
						ad.dispose();
				}
				if (catWindow != null) {
					if (catWindow.isVisible())
						catWindow.dispose();
				}
				if (eCW != null) {
					if (eCW.isVisible())
						eCW.dispose();
				}
			}

			JButton btnNewButton = new JButton("Logout");
		});
		btnNewButton.setBounds(12, 335, 130, 25);
		frmMain.getContentPane().add(btnNewButton);

		JButton btnNewButton_1 = new JButton("Refresh");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				appointmentsAktualisieren();
			}
		});
		btnNewButton_1.setBounds(150, 336, 130, 24);
		frmMain.getContentPane().add(btnNewButton_1);

		SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");

		tf_newPwd = new JPasswordField();
		tf_newPwd.setBounds(293, 330, 90, 25);

		tf_newPwdConfirm = new JPasswordField();
		tf_newPwdConfirm.setBounds(390, 330, 90, 25);

		final JLabel lblNewLabel = new JLabel("Confirm:");
		lblNewLabel.setBounds(390, 310, 70, 15);

		final JLabel lblNewLabel_1 = new JLabel("Enter new:");
		lblNewLabel_1.setBounds(295, 310, 88, 15);

		final JButton btn_savePwd = new JButton("Save");
		btn_savePwd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!tf_newPwd.getText().equals("")
						&& !tf_newPwdConfirm.getText().equals("")) {
					if (tf_newPwd.getText().equals(tf_newPwdConfirm.getText())) {
						JOptionPane.showMessageDialog(null, "Password changed",
								"Information", 1);
						instance.getUser().setPassword(tf_newPwd.getText());
						instance.editPerson(instance.getUser());
						frmMain.getContentPane().remove(tf_newPwd);
						frmMain.getContentPane().remove(tf_newPwdConfirm);
						frmMain.getContentPane().remove(btn_savePwd);
						frmMain.getContentPane().remove(lblNewLabel);
						frmMain.getContentPane().remove(lblNewLabel_1);
						frmMain.setSize(589, 393);
					} else
						JOptionPane.showMessageDialog(null,
								"Paswords not equal!", "Error", 0);
				} else
					JOptionPane.showMessageDialog(null,
							"Please enter a password!", "Error", 0);
			}
		});
		btn_savePwd.setBounds(487, 330, 79, 25);

		JButton btn_changePwd = new JButton("Change Pwd");
		btn_changePwd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frmMain.setSize(588, 400);
				frmMain.getContentPane().add(tf_newPwd);
				tf_newPwd.setText("");
				frmMain.getContentPane().add(tf_newPwdConfirm);
				tf_newPwdConfirm.setText("");
				frmMain.getContentPane().add(btn_savePwd);
				frmMain.getContentPane().add(lblNewLabel);
				frmMain.getContentPane().add(lblNewLabel_1);
			}
		});
		btn_changePwd.setBounds(12, 300, 130, 25);

		JButton btnUsers = new JButton("Users...");
		btnUsers.setBounds(12, 300, 117, 25);
		btnUsers.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				uw = new UserWindow(cw);
				uw.setVisible(true);
			}
		});

		if (instance.getUser().getIsAdmin() == true)
			frmMain.getContentPane().add(btnUsers);
		else {
			frmMain.getContentPane().add(btn_changePwd);
		}

		selectedCalendar = (Calendar) cb_calendar.getSelectedItem();
		calendarsAktualisieren();

		List<Appointment> liste = instance
				.abgelaufeneAppointments(selectedCalendar);
		if (liste != null && !liste.isEmpty()) {
			if (selectedCalendar != null) {
				Popup popup = new Popup(instance, selectedCalendar, liste);
				popup.setVisible(true);
			}
		}
	}

	public EditCalendarWindow geteCW() {
		return eCW;
	}

	public void seteCW(EditCalendarWindow eCW) {
		this.eCW = eCW;
	}

	public CategoryWindow getCatWindow() {
		return catWindow;
	}

	public void setCatWindow(CategoryWindow catWindow) {
		this.catWindow = catWindow;
	}

	public AppointmentDialog getAd() {
		return ad;
	}

	public void setAd(AppointmentDialog ad) {
		this.ad = ad;
	}

	public Administration getInstance() {
		return this.instance;
	}

	public Calendar getSelectedCalendar() {
		return selectedCalendar;
	}

	public void setSelectedDate(Date selectedDate) {
		this.selectedDate = selectedDate;
	}

	public Date getSelectedDate() {
		return selectedDate;
	}

	public void calendarsAktualisieren() {
		calendarModel.removeAllElements();
		if (instance.getUserCalendar() != null) {
			for (Calendar c : instance.getUserCalendar())
				calendarModel.addElement(c);
			return;
		}
		calendarModel.addElement("");
	}

	public void appointmentsAktualisieren() {
		List<Appointment> apps = instance.allDayAppointments(selectedDate,
				selectedCalendar);
		Collections.sort(apps, new AppointmentComparatorBegin());
		appointmentModel.removeAllElements();
		for (Appointment a : apps) {
			appointmentModel.addElement(a);
		}
	}
}